package cn.wolfcode.web.advices;

import cn.wolfcode.domain.JsonRequest;
import cn.wolfcode.web.exception.BusinessException;
import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@ControllerAdvice
public class ExceptionControllerAdvice {
//    统一处理异常,控制器的增强,控制器中的所有的异常都能被捕捉到
     @ExceptionHandler(BusinessException.class) //捕捉异常的类型 ,从上往下
    public void businessExceptionController(Exception e,HandlerMethod handlerMethod, HttpServletResponse response) throws IOException {//需要什么样的参数,底层都能拿到
//         判断报异常的方法返回的类型
         ResponseBody responseBody = handlerMethod.getMethodAnnotation(ResponseBody.class);
         if (responseBody==null){
//             页面
             e.printStackTrace();
             response.sendRedirect("/erro");
         }else{
//             JSON
             e.printStackTrace();
             response.setContentType("application/json;charset=utf-8");
             String string = JSON.toJSONString(new JsonRequest(false, e.getMessage()));
             response.getWriter().write(string);
         }

     }

     @ExceptionHandler(Exception.class) //捕捉异常的类型 ,从上往下
    public void exceptionController(Exception e,HandlerMethod handlerMethod, HttpServletResponse response) throws IOException {//需要什么样的参数,底层都能拿到
//         判断报异常的方法返回的类型
         ResponseBody responseBody = handlerMethod.getMethodAnnotation(ResponseBody.class);
         if (responseBody==null){
//             页面
             e.printStackTrace();
             response.sendRedirect("/erro");
         }else{
//             JSON
             e.printStackTrace();
             response.setContentType("application/json;charset=utf-8");
             String string = JSON.toJSONString(new JsonRequest(false, "系统异常,请联系管理员"));
             response.getWriter().write(string);
         }

     }

}
